package base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.SDKInitializer;
import com.google.gson.Gson;
import com.itboye.hutoubenjg.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;

import activity.MainOneActivity;
import activity.login.ActivityLogin;
import activity.messge.RepairMessActivity;
import activity.messge.SysTemMessgeActivity;
import bean.NotificationBean;
import util.util.db.SQLHelper;
import util.utls.Const;
import util.utls.SPUtils;

public class MyApplcation extends Application {

	public static MyApplcation ctx;

	private Toast toast;

	private List<WeakReference<Activity>> activityList = new LinkedList<>();

	protected String afterOpen;

	protected String activity;

	protected String extra;

	protected JSONObject jsonObject2;

	protected String afterOpen2;

	protected String order_code;

	protected String id;

	protected int type;

	protected JSONObject jsonObject;
	boolean isReadOne, isReadTwo;
	private SQLHelper sqlHelper;
	private static RequestQueue queue;
	public IWXAPI api;

	public static MyApplcation getInstance() {
		return ctx;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		api= WXAPIFactory.createWXAPI(this,null);
		api.registerApp(Const.APP_ID);
		ctx = this;
		SDKInitializer.initialize(getApplicationContext());
		queue = Volley.newRequestQueue(ctx);
		initImageLoader();
		initUMengPush();
	}

	private void initUMengPush() {
		mPushAgent = PushAgent.getInstance(this);
		mPushAgent.setDebugMode(true);
		//	通知声音由服务端控制
		mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);
		UmengMessageHandler messageHandler = new UmengMessageHandler() {
			/**
			 * 自定义消息的回调方法
			 * */
			@Override
			public void dealWithCustomMessage(final Context context,
											  final UMessage msg) {
				new Handler().post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						// 对自定义消息的处理方式，点击或者忽略
						boolean isClickOrDismissed = true;
						if (isClickOrDismissed) {
							// 自定义消息的点击统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgClick(msg);
						} else {
							// 自定义消息的忽略统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgDismissed(msg);
						}
						Toast.makeText(context, msg.custom, Toast.LENGTH_LONG)
								.show();
					}
				});
			}

			@Override
			public void dealWithNotificationMessage(Context arg0, UMessage arg1) {
				// TODO Auto-generated method stub
				super.dealWithNotificationMessage(arg0, arg1);
				Gson gson = new Gson();
				NotificationBean bean = gson.fromJson(arg1.getRaw().toString(),
						NotificationBean.class);
				if (bean.getBody().getActivity().equals("6180")) {// 更新列表
					Intent intent = new Intent("weixiu");
					sendBroadcast(intent);
					if(bean.getExtra().getRepair()!=null||!bean.getExtra().getRepair().equals("")){

					//	sdk关闭通知声音
					//	mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
					//	mPushAgent.setNotificationPlaySound(R.raw.umeng_push_notification_default_sound);

					}else{
						Intent intent01 = new Intent("weixiu");
						sendBroadcast(intent01);
					}
				}
			}

			/**
			 * 自定义通知栏样式的回调方法
			 * */
			@SuppressLint("NewApi")
			@Override
			public Notification getNotification(Context context, UMessage msg) {
				switch (msg.builder_id) {
					case 1:
						Notification.Builder builder = new Notification.Builder(
								context);
						RemoteViews myNotificationView = new RemoteViews(
								context.getPackageName(),
								R.layout.notification_view);
						myNotificationView.setTextViewText(R.id.notification_title,
								msg.title);
						myNotificationView.setTextViewText(R.id.notification_text,
								msg.text);
						myNotificationView.setImageViewBitmap(
								R.id.notification_large_icon,
								getLargeIcon(context, msg));
						myNotificationView.setImageViewResource(
								R.id.notification_small_icon,
								getSmallIconId(context, msg));
						builder.setContent(myNotificationView)
								.setSmallIcon(getSmallIconId(context, msg))
								.setTicker(msg.ticker).setAutoCancel(true);

						return builder.getNotification();
					default:
						// 默认为0，若填写的builder_id并不存在，也使用默认。
						return super.getNotification(context, msg);
				}
			}
		};
		mPushAgent.setMessageHandler(messageHandler);

		/**
		 * 自定义行为的回调处理 UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
		 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
		 * */
		UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
			@Override
			public void dealWithCustomAction(Context context, UMessage msg) {

			}

			@Override
			public void launchApp(Context context, UMessage uMessage) {
				super.launchApp(context, uMessage);
			}

			@Override
			public void openUrl(Context context, UMessage uMessage) {
				super.openUrl(context, uMessage);
			}

			@Override
			public void openActivity(Context arg0, UMessage arg1) {
				// TODO Auto-generated method stub
				// super.openActivity(arg0, arg1);//必须注释掉才能执行指定类的跳转
				Gson gson = new Gson();
				NotificationBean bean = gson.fromJson(arg1.getRaw().toString(),
						NotificationBean.class);
				Intent intent = new Intent();
				String uid = SPUtils.get(ctx, null, Const.ID, "")
						+ "";
				if (uid.equals("")) {
					intent = new Intent(ctx, ActivityLogin.class);
					startActivity(intent);
					return;
				}
				if (bean.getBody().getActivity().equals("6042")) {
					intent = new Intent(ctx, SysTemMessgeActivity.class);
					intent.putExtra("type", 1);
				} else if (bean.getBody().getActivity().equals("6180")) {
					if(bean.getExtra().getId()==null){
//||bean.getExtra().getId().equals("")
					//	intent = new Intent(ctx, DriverRepair.class);
						MainOneActivity.onSetFragment().setTabSelection(3);
					}else{
						intent = new Intent(ctx, RepairMessActivity.class);
					}

				} else if (bean.getBody().getActivity().equals("6074")) {
					intent = new Intent(ctx, RepairMessActivity.class);
					intent.putExtra("type", 4);
				}
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}


		};
		// 使用自定义的NotificationHandler，来结合友盟统计处理消息通知
		// 参考http://bbs.umeng.com/thread-11112-1-1.html
		// CustomNotificationHandler notificationClickHandler = new
		// CustomNotificationHandler();
		mPushAgent.setNotificationClickHandler(notificationClickHandler);

		// 注册推送服务 每次调用register都会回调该接口
		mPushAgent.register(new IUmengRegisterCallback() {
			@Override
			public void onSuccess(String deviceToken) {
				System.out.println(">>>" + deviceToken);

			}

			@Override
			public void onFailure(String s, String s1) {

			}
		});

	}

	/** 获取Application */
	/** 获取数据库Helper */
	public SQLHelper getSQLHelper() {
		if (sqlHelper == null)
			sqlHelper = new SQLHelper(ctx);
		return sqlHelper;
	}

	/** 摧毁应用进程时候调用 */
	public void onTerminate() {
		if (sqlHelper != null)
			sqlHelper.close();
		super.onTerminate();
	}


	public void showNetWorkError() {
		if (toast == null) {
			toast = Toast.makeText(MyApplcation.ctx, "", Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.setView(LayoutInflater.from(MyApplcation.ctx).inflate(
					R.layout.dialog_network_error, null));
		}

		toast.show();
	}

	public void addActivity(Activity activity) {
		activityList.add(new WeakReference<Activity>(activity));
	}

	// 遍历所有Activity并finish
	public void exit() {
		for (WeakReference<Activity> activity : activityList) {
			if (activity.get() != null) {
				activity.get().finish();
			}

		}
		System.exit(0);
	}

	/**
	 * @return the queue
	 */
	public static RequestQueue getQueue() {
		return queue;
	}
//
	public static <T> void addRequest(Request<T> request) {
		request.addMarker("itboye");
		getQueue().add(request);
	}


	public PushAgent mPushAgent;

	public PushAgent getmPushAgent() {
		return mPushAgent;
	}


//	private static RequestQueue queue;

	// private List<WeakReference<Activity>> activitys = new
	// ArrayList<WeakReference<Activity>>();

	// private UncaughtExceptionHandler exceptionHandler;
	public void initImageLoader() {
		long maxMamory = Runtime.getRuntime().maxMemory();// 应用程序程序运行时所使用最大内存数
		maxMamory = (long) (maxMamory * 0.7);
		int v = Runtime.getRuntime().availableProcessors();
		int availableProcessors = v < 4 ? 3 : v - 1;

		// System.out.println("maxMamory : " + maxMamory +
		// "  availableProcessors: " + availableProcessors);

		// DebugToast.show("maxMamory : " + (maxMamory/1024.0f/1024 )+
		// "  availableProcessors: " + availableProcessors, 1);

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				// 设置图片下载期间显示的图片
				.showImageOnLoading(R.drawable.ad_default2)
				.showImageForEmptyUri(R.drawable.ad_default2)// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.ad_default2) // 设置图片加载或解码过程中发生错误显示的图片
				.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
				.cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
				.bitmapConfig(Bitmap.Config.RGB_565)
				// .displayer(new RoundedBitmapDisplayer(20))// 设置成圆角图片
				.build(); // 创建配置过得DisplayImageOption对象 

		// File cacheDir = StorageUtils.getOwnCacheDirectory(App.ctx,
		// "sunsun/Cache");
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				ctx)
				.memoryCacheExtraOptions(480, 800)
				// max width, max
				// height，即保存的每个缓存文件的最大长宽
				// .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75,
				// null) // Can slow ImageLoader, use it carefully (Better don't
				// use it)/设置缓存的详细信息，最好不要设置这个
				.threadPoolSize(availableProcessors)
				// 线程池内加载的数量
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 *
				// 1024)) // You can pass your own memory cache
				// implementation/你可以通过自己的内存缓存实现
				// .memoryCache(new WeakMemoryCache())

				.memoryCacheSize((int) maxMamory)
				// .memoryCacheSize(15 * 1024 * 1024)

				.diskCacheSize(80 * 1024 * 1024)
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
				// 加密

				.tasksProcessingOrder(QueueProcessingType.LIFO) // 后进先出
				// .diskCacheFileCount(100) //缓存的文件数量
				// .diskCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
				// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.defaultDisplayImageOptions(options)
				// .imageDownloader(new BaseImageDownloader(App.ctx, 5 * 1000,
				// 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
				// .imageDownloader(new DownloadImageFromNetWork(App.ctx, 5 *
				// 1000, 30 * 1000)).writeDebugLogs() // Remove
				// for
				// release
				// app
				.build();// 开始构建
		// Initialize ImageLoader with configuration.

		com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(
				config);// 全局初始化此配置
	}
}
